package com.dao.impl;

import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;

import com.bean.House;
import com.bean.SearchCondition;
import com.dao.HouseDao;

public class HouseDaoImpl implements HouseDao {

	@Override
	public List<House> search(SearchCondition sc, int pageIndex) {
		Session session = null;
		try {
			session = HibernateUtil.getSession();
			String hql = this.getSql(sc);
			System.out.println(hql);
			Query query = session.createQuery(hql);
			query.setFirstResult((pageIndex - 1) * 10);
			query.setMaxResults(10);
			return query.list();
		} finally {
			if (session != null)
				session.close();
		}
	}

	@Override
	public int getTotal(SearchCondition sc) {
		Session session = null;
		try {
			session = HibernateUtil.getSession();
			String sql = "";
			sql = "select count(*) ";
			sql += this.getSql(sc);
			Query query = session.createQuery(sql);
			return Integer.valueOf(query.uniqueResult() + "");

		} finally {
			if (session != null)
				session.close();
		}
	}

	// 生成sql语句
	public String getSql(SearchCondition sc) {
		StringBuffer sb = new StringBuffer();
		sb.append("from House h where 1 = 1");
		if (sc.getDistrictId() != 0)
			sb.append(" and h.street.district.id =" + sc.getDistrictId());
		if (sc.getStreetId() != 0)
			sb.append(" and h.street.id =" + sc.getStreetId());
		if (sc.getFromPrice() != 0)
			sb.append(" and h.price >" + sc.getFromPrice());
		if (sc.getToPrice() != 0)
			sb.append(" and h.price <" + sc.getToPrice());
		if (sc.getHouseTypeId() != 0)
			sb.append(" and h.houseType.id =" + sc.getHouseTypeId());
		if (sc.getTypeId() != 0)
			sb.append(" and h.type.id =" + sc.getTypeId());
		return sb.toString();
	}

	// 根据id获取房屋
	@Override
	public House get(int id) {
		return (House) HibernateUtil.get(House.class, id);
	}

	// 添加房屋
	@Override
	public void add(House house) {
		HibernateUtil.add(house);
	}

}
